package com.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dto.OrdersAddForm;
import com.dto.OrdersMO;
import com.dto.OrdersSearchForm;
import com.dto.ReportForm;
import com.entity.MaterialInput;
import com.entity.OrderDetail;
import com.entity.Orders;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.MaterialInputMapper;
import com.mapper.OrderDetailMapper;
import com.mapper.OrdersMapper;
import com.service.OrdersService;
import com.utils.CommonUtils;
import com.utils.PageObject;
import com.vo.OrdersVO;
import com.vo.ReportVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  入库订单服务实现类
 * </p>
 *
 * @author aiou
 * @since 2025-06-10
 */
@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private MaterialInputMapper materialInputMapper;

    //分页查询
    @Override
    public PageObject<OrdersVO> list(PageObject pageObject, OrdersSearchForm form) {
        //开始分页
        PageHelper.startPage(pageObject.getCurrent(),pageObject.getSize());
        //查询数据
        List<OrdersVO> list = ordersMapper.list(form);
        //PageHelper包装数据
        PageInfo<OrdersVO> pageInfo = new PageInfo<>(list);
        //将数据封装进PageResult
        PageObject<OrdersVO> userPageResult
                = new PageObject<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return userPageResult;
    }

    //批量删除
    @Override
    public boolean batchDelete(String orderNoArr) {
        String[] split = orderNoArr.split(",");
        List<String> orderNoList = new ArrayList<>();
        for (String orderNo : split) {
            orderNoList.add(orderNo);
        }
        OrdersMO ordersMO = new OrdersMO();
        ordersMO.setOrderNos(orderNoList);
        //删除订单
        int i = this.ordersMapper.batchDelete(ordersMO);
        if(i == 0) return false;
        //删除订单详情
        int i1 = this.orderDetailMapper.batchDelete(ordersMO);
        if(i1 == 0) return false;
        return true;
    }

    //批量审核
    @Override
    public boolean batchVerify(String orderNoArr) {
        String[] split = orderNoArr.split(",");
        List<String> orderNoList = new ArrayList<>();
        for (String orderNo : split) {
            orderNoList.add(orderNo);
        }
        OrdersMO ordersMO = new OrdersMO();
        ordersMO.setOrderNos(orderNoList);
        int i = this.ordersMapper.batchVerify(ordersMO);
        if(i == 0) return false;
        return true;
    }

    //批量作废
    @Override
    public boolean batchInvalid(String orderNoArr) {
        String[] split = orderNoArr.split(",");
        List<String> orderNoList = new ArrayList<>();
        for (String orderNo : split) {
            orderNoList.add(orderNo);
        }
        OrdersMO ordersMO = new OrdersMO();
        ordersMO.setOrderNos(orderNoList);
        int i = this.ordersMapper.batchInvalid(ordersMO);
        if(i == 0) return false;
        return true;
    }

    //新增订单
    @Override
    public boolean save(OrdersAddForm ordersAddForm) {
        //todo:1、保存Orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddForm, orders);
        //自动生成order_no
        Integer count = this.ordersMapper.selectCount();
        orders.setOrderNo(CommonUtils.createOrderNo(count,ordersAddForm.getOrderType()));
        //固定写操作员名称
        orders.setEmployeeName("小明");
        if(StringUtils.isNotBlank(ordersAddForm.getOrderDate())){
            orders.setOrderDate(CommonUtils.parseString2(ordersAddForm.getOrderDate()));
        } else {
            orders.setOrderDate(LocalDateTime.now());
        }
        int insert = this.ordersMapper.insert(orders);
        if(insert == 0) return false;
        //保存OrderDetail
        String orderDetailsStr = ordersAddForm.getOrderDetailsStr();
        String[] split = orderDetailsStr.split("&");
        for (String orderDetailStr : split) {
            String[] split1 = orderDetailStr.split(",");
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setMaterialId(Integer.parseInt(split1[0]));
            orderDetail.setMaterialCode(split1[1]);
            orderDetail.setMaterialName(split1[2]);
            orderDetail.setStyle(split1[3]);
            orderDetail.setUnitName(split1[4]);
            orderDetail.setOrderId(split1[5]);
            orderDetail.setBatchNo(split1[6]);
            orderDetail.setOrderFlag(split1[8]);
            if(orderDetail.getOrderFlag().equals("冲红")){
                orderDetail.setOrderCount(new BigDecimal("-"+split1[7]));
            } else {
                orderDetail.setOrderCount(new BigDecimal(split1[7]));
            }
            orderDetail.setStorageId(Integer.parseInt(split1[9]));
            orderDetail.setStorageName(split1[10]);
            orderDetail.setOrderNo(orders.getOrderNo());
            int insert1 = this.orderDetailMapper.insert(orderDetail);
            if(insert1 == 0) return false;
        }
        return true;
    }

    //根据订单编号查询订单
    @Override
    public Orders selectByOrderNo(String orderNo) {
        return ordersMapper.selectByOrderNo(orderNo);
    }

    //修改订单信息
    @Override
    public boolean update(OrdersAddForm ordersAddForm) {
        //更新Orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddForm, orders);
//        Integer count = this.ordersMapper.selectCount();
        orders.setEmployeeName("小明");
        if(StringUtils.isNotBlank(ordersAddForm.getOrderDate())){
            orders.setOrderDate(CommonUtils.parseString2(ordersAddForm.getOrderDate()));
        } else {
            orders.setOrderDate(LocalDateTime.now());
        }
        int updateById = this.ordersMapper.update(orders);
        if(updateById == 0) return false;
        //删除旧OrderDetail
        int delete = this.orderDetailMapper.delete(orders.getOrderNo());
        if(delete == 0) return false;
        String orderDetailsStr = ordersAddForm.getOrderDetailsStr();
        String[] split = orderDetailsStr.split("&");
        for (String orderDetailStr : split) {
            String[] split1 = orderDetailStr.split(",");
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setMaterialId(Integer.parseInt(split1[0]));
            orderDetail.setMaterialCode(split1[1]);
            orderDetail.setMaterialName(split1[2]);
            orderDetail.setStyle(split1[3]);
            orderDetail.setUnitName(split1[4]);
            orderDetail.setOrderId(split1[5]);
            orderDetail.setBatchNo(split1[6]);
            orderDetail.setOrderFlag(split1[8]);
            if(orderDetail.getOrderFlag().equals("冲红")){
                orderDetail.setOrderCount(new BigDecimal("-"+split1[7]));
            } else {
                orderDetail.setOrderCount(new BigDecimal(split1[7]));
            }
            orderDetail.setStorageId(Integer.parseInt(split1[9]));
            orderDetail.setStorageName(split1[10]);
            orderDetail.setOrderNo(orders.getOrderNo());
            //插入新的OrderDetail
            int insert1 = this.orderDetailMapper.insert(orderDetail);
            if(insert1 == 0) return false;
        }
        return true;
    }

    //订单详情：单个删除
    @Override
    public boolean delete(String orderNo) {
        int delete = ordersMapper.delete(orderNo);
        if(delete == 0) return false;
        int delete1 = orderDetailMapper.delete(orderNo);
        if(delete1 == 0) return false;
        return true;
    }

    //订单详情：单个审核
    @Override
    public boolean verify(String orderNo) {
        Orders orders = ordersMapper.selectOne(orderNo);
        orders.setStatus(1);
        int update = this.ordersMapper.update(orders);
        if(update == 0) return false;
        return true;
    }

    //订单详情：单个作废
    @Override
    public boolean invalid(String orderNo) {
        Orders orders = this.ordersMapper.selectOne(orderNo);
        orders.setInvalid(0);
        int update = this.ordersMapper.update(orders);
        if(update == 0) return false;
        return true;
    }

    //采购退货单：分页查询
    @Override
    public PageObject ordersReturnList(PageObject pageObject, OrdersSearchForm form) {
        //开始分页
        PageHelper.startPage(pageObject.getCurrent(),pageObject.getSize());
        //查询数据
        List<OrdersVO> list = ordersMapper.ordersReturnVOList(form);
        //PageHelper包装数据
        PageInfo<OrdersVO> pageInfo = new PageInfo<>(list);
        //将数据封装进PageResult
        PageObject<OrdersVO> ordersReturnPageResult
                = new PageObject<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return ordersReturnPageResult;
    }

    //采购退货单：新增退货单
    @Override
    public boolean ordersReturn(OrdersAddForm ordersAddForm) {
        //保存Orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddForm, orders);
        Integer count = this.ordersMapper.selectCount();
        orders.setOrderNo(CommonUtils.createOrderNo(count,ordersAddForm.getOrderType()));
        orders.setEmployeeName("小明");
        if(StringUtils.isNotBlank(ordersAddForm.getOrderDate())){
            orders.setOrderDate(CommonUtils.parseString2(ordersAddForm.getOrderDate()));
        } else {
            orders.setOrderDate(LocalDateTime.now());
        }
        int insert = this.ordersMapper.insert(orders);
        if(insert == 0) return false;
        //保存OrderDetail
        String orderDetailsStr = ordersAddForm.getOrderDetailsStr();
        String[] split = orderDetailsStr.split("&");
        for (String orderDetailStr : split) {
            String[] split1 = orderDetailStr.split(",");
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setMaterialId(Integer.parseInt(split1[0]));
            orderDetail.setMaterialCode(split1[1]);
            orderDetail.setMaterialName(split1[2]);
            orderDetail.setStyle(split1[3]);
            orderDetail.setUnitName(split1[4]);
            orderDetail.setOrderId(split1[5]);
            orderDetail.setBatchNo(split1[6]);
            orderDetail.setOrderFlag(split1[8]);
            if(orderDetail.getOrderFlag().equals("冲红")){
                orderDetail.setOrderCount(new BigDecimal("-"+split1[7]));
                //修改入库订单的库存
                //根据批号获取订单的数量
                //传参为：(batchNo,orderType)
                BigDecimal orderCount = this.orderDetailMapper.getOrderCount(split1[6], 1);
                //订单数量-退货数量
                BigDecimal add = orderCount.add(new BigDecimal(split1[7]));
                //更新对应批号订单的订单数量
                int updateOrderCount = this.orderDetailMapper.updateOrderCount(add, split1[6], 1);
                if(updateOrderCount == 0) return false;
            } else {
                orderDetail.setOrderCount(new BigDecimal(split1[7]));
                //修改入库订单的库存
                BigDecimal orderCount = this.orderDetailMapper.getOrderCount(split1[6], 1);
                BigDecimal subtract = orderCount.subtract(new BigDecimal(split1[7]));
                int updateOrderCount = this.orderDetailMapper.updateOrderCount(subtract, split1[6], 1);
                if(updateOrderCount == 0) return false;
            }
            orderDetail.setStorageId(Integer.parseInt(split1[9]));
            orderDetail.setStorageName(split1[10]);
            orderDetail.setOrderNo(orders.getOrderNo());
            int insert1 = this.orderDetailMapper.insert(orderDetail);
            if(insert1 == 0) return false;
        }
        return true;
    }

    //销售订单：分页查询
    @Override
    public PageObject saleList(PageObject pageObject, OrdersSearchForm form) {
        //开始分页
        PageHelper.startPage(pageObject.getCurrent(),pageObject.getSize());
        //查询数据
        List<OrdersVO> list = ordersMapper.saleVOList(form);
        //PageHelper包装数据
        PageInfo<OrdersVO> pageInfo = new PageInfo<>(list);
        //将数据封装进PageResult
        PageObject<OrdersVO> salesPageResult
                = new PageObject<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return salesPageResult;
    }

    //销售出库单：新增订单
    @Override
    public boolean saleSave(OrdersAddForm ordersAddForm) {
        //保存Orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddForm, orders);
        Integer count = this.ordersMapper.selectCount();
        orders.setOrderNo(CommonUtils.createOrderNo(count,ordersAddForm.getOrderType()));
        orders.setEmployeeName("小明");
        if(StringUtils.isNotBlank(ordersAddForm.getOrderDate())){
            orders.setOrderDate(CommonUtils.parseString2(ordersAddForm.getOrderDate()));
        } else {
            orders.setOrderDate(LocalDateTime.now());
        }
        int insert = this.ordersMapper.insert(orders);
        if(insert == 0) return false;
        //保存OrderDetail
        String orderDetailsStr = ordersAddForm.getOrderDetailsStr();
        String[] split = orderDetailsStr.split("&");
        for (String orderDetailStr : split) {
            String[] split1 = orderDetailStr.split(",");
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setMaterialId(Integer.parseInt(split1[0]));
            orderDetail.setMaterialCode(split1[1]);
            orderDetail.setMaterialName(split1[2]);
            orderDetail.setStyle(split1[3]);
            orderDetail.setUnitName(split1[4]);
            orderDetail.setOrderId(split1[5]);
            orderDetail.setBatchNo(split1[6]);
            orderDetail.setOrderFlag(split1[8]);
            if(orderDetail.getOrderFlag().equals("冲红")){
                orderDetail.setOrderCount(new BigDecimal("-"+split1[7]));
                BigDecimal orderCount = this.orderDetailMapper.getOrderCount(split1[6], 1);
                BigDecimal add = orderCount.add(new BigDecimal(split1[7]));
                int updateOrderCount = this.orderDetailMapper.updateOrderCount(add, split1[6], 1);
                if(updateOrderCount == 0) return false;
            } else {
                orderDetail.setOrderCount(new BigDecimal(split1[7]));
                BigDecimal orderCount = this.orderDetailMapper.getOrderCount(split1[6], 1);
                BigDecimal subtract = orderCount.subtract(new BigDecimal(split1[7]));
                int updateOrderCount = this.orderDetailMapper.updateOrderCount(subtract, split1[6], 1);
                if(updateOrderCount == 0) return false;
            }
            orderDetail.setStorageId(Integer.parseInt(split1[9]));
            orderDetail.setStorageName(split1[10]);
            orderDetail.setOrderNo(orders.getOrderNo());
            int insert1 = this.orderDetailMapper.insert(orderDetail);
            if(insert1 == 0) return false;
        }
        return true;
    }

    //销售退货单：分页查询
    @Override
    public Object saleReturnList(PageObject pageObject, OrdersSearchForm form) {
        //开始分页
        PageHelper.startPage(pageObject.getCurrent(),pageObject.getSize());
        //查询数据
        List<OrdersVO> list = ordersMapper.saleReturnVOList(form);
        //PageHelper包装数据
        PageInfo<OrdersVO> pageInfo = new PageInfo<>(list);
        //将数据封装进PageResult
        PageObject<OrdersVO> salesReturnPageResult
                = new PageObject<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return salesReturnPageResult;
    }

    //销售退货单：新增订单
    @Override
    public boolean saleReturn(OrdersAddForm ordersAddForm) {
        //保存Orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersAddForm, orders);
        Integer count = this.ordersMapper.selectCount();
        orders.setOrderNo(CommonUtils.createOrderNo(count,ordersAddForm.getOrderType()));
        orders.setEmployeeName("小明");
        if(StringUtils.isNotBlank(ordersAddForm.getOrderDate())){
            orders.setOrderDate(CommonUtils.parseString2(ordersAddForm.getOrderDate()));
        } else {
            orders.setOrderDate(LocalDateTime.now());
        }
        int insert = this.ordersMapper.insert(orders);
        if(insert == 0) return false;
        //保存OrderDetail
        String orderDetailsStr = ordersAddForm.getOrderDetailsStr();
        String[] split = orderDetailsStr.split("&");
        for (String orderDetailStr : split) {
            String[] split1 = orderDetailStr.split(",");
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setMaterialId(Integer.parseInt(split1[0]));
            orderDetail.setMaterialCode(split1[1]);
            orderDetail.setMaterialName(split1[2]);
            orderDetail.setStyle(split1[3]);
            orderDetail.setUnitName(split1[4]);
            orderDetail.setOrderId(split1[5]);
            orderDetail.setBatchNo(split1[6]);
            orderDetail.setOrderFlag(split1[8]);
            if(orderDetail.getOrderFlag().equals("冲红")){
                orderDetail.setOrderCount(new BigDecimal("-"+split1[7]));
                //修改入库订单的库存
                BigDecimal orderCount = this.orderDetailMapper.getOrderCount(split1[6], 1);
                BigDecimal subtract = orderCount.subtract(new BigDecimal(split1[7]));
                int updateOrderCount = this.orderDetailMapper.updateOrderCount(subtract, split1[6], 1);
                if(updateOrderCount == 0) return false;
            } else {
                orderDetail.setOrderCount(new BigDecimal(split1[7]));
                //修改入库订单的库存
                BigDecimal orderCount = this.orderDetailMapper.getOrderCount(split1[6], 1);
                BigDecimal add = orderCount.add(new BigDecimal(split1[7]));
                int updateOrderCount = this.orderDetailMapper.updateOrderCount(add, split1[6], 1);
                if(updateOrderCount == 0) return false;
            }
            orderDetail.setStorageId(Integer.parseInt(split1[9]));
            orderDetail.setStorageName(split1[10]);
            orderDetail.setOrderNo(orders.getOrderNo());
            int insert1 = this.orderDetailMapper.insert(orderDetail);
            if(insert1 == 0) return false;
        }
        return true;
    }

    //仓库明细：分页查询
    @Override
    public PageObject reportList(PageObject pageObject, ReportForm form) {
        //开始分页
        PageHelper.startPage(pageObject.getCurrent(),pageObject.getSize());
        //查询数据
        List<ReportVO> list = ordersMapper.reportList(form);
        //PageHelper包装数据
        PageInfo<ReportVO> pageInfo = new PageInfo<>(list);
        //将数据封装进PageResult
        PageObject<ReportVO> userPageResult
                = new PageObject<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return userPageResult;
    }

    //仓库明细：Excel导出(查询Excel内容)
    @Override
    public List<ReportVO> reportList() {
        return this.ordersMapper.reportExportList();
    }

    //采购退货单：入库
    @Override
    public boolean inStore(String idArray, String name) {
        String [] array = idArray.split(",");
        for (String id : array) {
            //存储orders
            MaterialInput materialInput = materialInputMapper.selectById(id);
            Integer count = this.ordersMapper.selectCount();
            String orderNo = CommonUtils.createOrderNo(count,1);
            Orders orders = new Orders(0, 1, 1, LocalDateTime.now(),materialInput.getOrderDate());
            orders.setOrderNo(orderNo);
            orders.setSupplierId(materialInput.getSupplierId());
            orders.setVerifyPerson(name);
            orders.setEmployeeName(name);
            int insert = this.ordersMapper.insert(orders);
            if(insert == 0) return false;
            //存储orderdetail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(materialInput, orderDetail);
            orderDetail.setOrderNo(orders.getOrderNo());
            orderDetail.setOrderFlag("正常");
            int insert1 = this.orderDetailMapper.insert(orderDetail);
            if(insert1 == 0) return false;
            //修改materialinput的状态
            materialInput.setStatus(2);
            materialInput.setOrderNo(orders.getOrderNo());
            int update = this.materialInputMapper.updateById(materialInput);
            if(update == 0) return false;
        }
        return true;
    }

}
